package com.huan.api

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

/**
 * json的使用
 * @author huan.fu
 * @date 2024/6/23 - 16:58
 */
class Json {

    static void main(String[] args) {
        Person.Address address1 = new Person.Address("湖北", 1)
        Person.Address address2 = new Person.Address("湖南", 2)

        Person person = new Person();
        person.age = 18;
        person.name = "张三";
        person.address = [address1, address2]
        person.map = ["aa": "aaa", "bb": "bbb"]
        person.date = new Date();
        person.flag = true;

        // 转换成json
        def json = JsonOutput.toJson(person)
        println json

        // 解析json
        def slurper = new JsonSlurper()
        def jsonObj = slurper.parseText(json)

        println jsonObj.age
        println jsonObj.name
        println jsonObj.map
        println jsonObj.map['aa']
        println jsonObj.address
        println jsonObj.address[0].address
        println jsonObj.date
        println jsonObj.flag




    }

    static class Person {
        int age;
        String name;
        List<Address> address;
        def map;
        def date;
        def flag;


        static class Address {
            private String address;
            private int priority;

            Address() {}

            Address(String address, int priority) {
                this.address = address
                this.priority = priority
            }

            String getAddress() {
                return address
            }

            void setAddress(String address) {
                this.address = address
            }

            int getPriority() {
                return priority
            }

            void setPriority(int priority) {
                this.priority = priority
            }
        }

        int getAge() {
            return age
        }

        void setAge(int age) {
            this.age = age
        }

        String getName() {
            return name
        }

        void setName(String name) {
            this.name = name
        }

        List<Address> getAddress() {
            return address
        }

        void setAddress(List<Address> address) {
            this.address = address
        }

        def getMap() {
            return map
        }

        void setMap(map) {
            this.map = map
        }

        def getDate() {
            return date
        }

        void setDate(date) {
            this.date = date
        }

        def getFlag() {
            return flag
        }

        void setFlag(flag) {
            this.flag = flag
        }
    }

}
